<template>
<div class="details-content">
  <h1 class="title">{{article.title}}</h1>
  <div class="info">
    <a-space align="center" size="large">
      <div>
        <UserOutlined />
        作者: {{article.author.name}}
      </div>
      <div>
        <FieldTimeOutlined />
        发布时间: {{article.created_at}}
      </div>
      <div>
        <MailOutlined />
        通讯邮箱: {{article.author.email}}
      </div>
    </a-space>
  </div>
  <div class="content">
    <v-md-preview ref="preview" :text="article.content" />
  </div>
</div>
</template>

<script setup>
import {UserOutlined, FieldTimeOutlined, MailOutlined} from "@ant-design/icons-vue";
import {onMounted, ref, defineExpose} from "vue";
import Anchors from './Anchors.vue'

defineProps({
  article: Object
})

const preview = ref(null)

const tocAnchors = ref([])

const emit = defineEmits(['anchor'])

onMounted(() => {
  const anchors = preview.value.$el.querySelectorAll('h1,h2')
  let count = 0;
  Array.from(anchors).forEach(el => {
    // 添加锚点id
    const anchorId = 'custom-anchor-' + count++
    el.id = anchorId
    // 生成锚点序列
    const anchor = {
      indent: parseInt(el.tagName.charAt(1)),
      title: el.innerText.trim(),
      anchor: '#' + anchorId,
      child: []
    }
    // 存储序列
    if (anchor.indent === 1) {
      tocAnchors.value.push(anchor)
      return
    }
    tocAnchors.value[tocAnchors.value.length - 1].child.push(anchor)
  })
  emit('anchor', tocAnchors.value)
})

defineExpose({
  preview
})
</script>

<style scoped>
.title {
  text-align: center;
}

.info {
  display: flex;
  justify-content: center;
  color: #999999;
}
</style>